﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using GoShopping.BLL;
using GoShopping.Model;

namespace GoShopping.Web
{
    public partial class MyUserInfo : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GetOrderPrdts();
                GetUserAddr();
                SetWizardStyle();
                ResponseCityOrCounty();
            }
        }

        private void GetUserAddr()
        {
            GoShopping.BLL.UserBean ub = new UserBean();
            GoShopping.BLL.ProfileInfo.AddressListBean alb = new GoShopping.BLL.ProfileInfo.AddressListBean();
            IList<GoShopping.Model.AddressList> addrList = alb.GetUserAddressList(ub.GetOneUser(Context.User.Identity.Name).ID);
            if (addrList.Count != 0)
            {
                lblName.Text = addrList[0].AcceptPeople;
                lblAddress.Text = GetRelatedColumn.GetProvinceName(addrList[0].ProvinceID) + " " + GetRelatedColumn.GetCityName(addrList[0].CityID) + " " + GetRelatedColumn.GetCountyName(addrList[0].CountyID) + " " + addrList[0].DetailStreet;
                lblPhone.Text = addrList[0].AcceptPeopleMobileTel;
                lblZipCode.Text = addrList[0].ZipCode;
            }
            else
            {
                lblName.Text = "无";
                lblAddress.Text = "无";
                lblPhone.Text = "无";
                lblZipCode.Text = "无";
            }
        }

        /// <summary>
        /// 选择已有地址并返回订单确认页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSelectAddr_Click(object sender, EventArgs e)
        {
            if (GetRptSelected(RptAddress) == null)
            {
                ScriptManager.RegisterStartupScript(UpdatePanel1, GetType(), "click", "<script>alert('请选择一个地址！');</script>", false);
                return;
            }
            else
            {
                string[] userAddr = GetRptSelected(RptAddress).Split(' ');
                lblAddress.Text = userAddr[0] + " " + userAddr[1] + " " + userAddr[2] + " " + userAddr[3];
                lblZipCode.Text = userAddr[4];
                lblPhone.Text = userAddr[5];
                lblName.Text = userAddr[6];
            }
            Wizard1.ActiveStepIndex = 0;
        }
        /// <summary>
        /// 增加新的地址并返回订单确认页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnEditAddr_Click(object sender, EventArgs e)
        {
            Wizard1.ActiveStepIndex = 1;
            GetAddressList();
            SetProvinceDDL();
        }

        private void GetOrderPrdts()
        {
            RptOrderList.DataSource = Profile.grpShoppingCart.MyCart.Items;
            RptOrderList.DataBind();
        }

        #region Wizard Event
        protected void Wizard1_NextButtonClick(object sender, WizardNavigationEventArgs e)
        {
            GoShopping.BLL.UserBean ub = new GoShopping.BLL.UserBean();
            GoShopping.Model.UserInfo ui = ub.GetOneUser(Context.User.Identity.Name);
            GoShopping.BLL.ProfileInfo.AddressListBean alb = new GoShopping.BLL.ProfileInfo.AddressListBean();
            GoShopping.Model.AddressList al = new AddressList();
            switch (e.CurrentStepIndex)
            {
                case 0:
                    {
                        GiftCard gc = new GiftCard();
                        BLL.SysInfo.GiftCardBean gcb = new GoShopping.BLL.SysInfo.GiftCardBean();
                        if (txtGiftCard.Text != "")
                        {
                            if (gcb.GetGiftCard(txtGiftCard.Text.Trim()) == null)
                            {
                                ScriptManager.RegisterStartupScript(UpdatePanel1, GetType(), "click", "<script>alert('礼品卡不存在！');</script>", false);
                                e.Cancel = true;
                                return;
                            }
                        }
                        IList<GoShopping.Model.OrderEachProduct> oeps;
                        GoShopping.Model.Order od;
                        GoShopping.BLL.Orders.OrderBean ob;
                        string orderCode;
                        string addr = lblName.Text + "," + lblAddress.Text + "," + lblZipCode.Text + "," + lblPhone.Text;
                        if (string.IsNullOrEmpty(addr.Trim()))
                        {
                            ScriptManager.RegisterStartupScript(UpdatePanel1, GetType(), "click", "<script>alert('请选择一个地址！');</script>", false);
                            e.Cancel = true;
                            return;
                        }
                        try
                        {
                            if (CreateOrderList(out oeps, out od, out ob, addr, "货到付款"))
                            {
                                ob.CreateOrder(oeps, od, out orderCode);
                                lblOrderCode.Text = orderCode;
                                Profile.grpShoppingCart.MyCart.Items = null;
                                Wizard1.ActiveStepIndex = 2;
                            }
                        }
                        catch (Exception ex)
                        {
                            ScriptManager.RegisterStartupScript(UpdatePanel1, GetType(), "click", string.Format("<script>alert('创建订单失败！{0}');</script>", ex.Message), false);
                            e.Cancel = true;
                            return;
                        }
                    } break;
            }
        }

        protected void Wizard1_PreviousButtonClick(object sender, WizardNavigationEventArgs e)
        {
            GoShopping.BLL.UserBean ub = new GoShopping.BLL.UserBean();
            GoShopping.Model.UserInfo ui = ub.GetOneUser(Context.User.Identity.Name);
            GoShopping.BLL.ProfileInfo.AddressListBean alb = new GoShopping.BLL.ProfileInfo.AddressListBean();
            GoShopping.Model.AddressList al = new AddressList();
            if (Wizard1.ActiveStepIndex == 1)
            {
                AddNewAddress(ui, alb, al);
                lblName.Text = al.AcceptPeople;
                lblAddress.Text = GetRelatedColumn.GetProvinceName(al.ProvinceID) + " " + GetRelatedColumn.GetCityName(al.CityID) + " " + GetRelatedColumn.GetCountyName(al.CountyID) + " " + al.DetailStreet;
                lblZipCode.Text = al.ZipCode;
                if (al.AcceptPeopleMobileTel == "")
                {
                    lblPhone.Text = al.AcceptPeopleTel;
                }
                else
                {
                    lblPhone.Text = al.AcceptPeopleMobileTel;
                }
            }
        }
        #endregion

        #region 订单数据获取
        /// <summary>
        /// 创建订单的数据
        /// </summary>
        /// <param name="oeps"></param>
        /// <param name="od"></param>
        /// <param name="ob"></param>
        private bool CreateOrderList(out IList<GoShopping.Model.OrderEachProduct> oeps, out GoShopping.Model.Order od, out GoShopping.BLL.Orders.OrderBean ob, string address, string sendWay)
        {
            GoShopping.BLL.UserBean ub = new GoShopping.BLL.UserBean();
            GoShopping.Model.UserInfo ui = ub.GetOneUser(Context.User.Identity.Name);
            oeps = new List<GoShopping.Model.OrderEachProduct>();
            foreach (CartItem ci in Profile.grpShoppingCart.MyCart.Items)
            {
                GoShopping.Model.OrderEachProduct oep = new GoShopping.Model.OrderEachProduct();
                //oep.OrderID = i++;
                oep.ProductID = Convert.ToInt32(ci.ItemId);
                oep.UnitPrice = Convert.ToInt32(ci.ItemPrice);
                oep.Quantity = ci.Count;
                oeps.Add(oep);
            }
            od = new GoShopping.Model.Order();
            ob = new GoShopping.BLL.Orders.OrderBean();
            string[] userAddr = address.Split(',');
            string[] userAddr1 = userAddr[1].Split(' ');
            if (lblName.Text == "无" || lblAddress.Text == "无" || lblZipCode.Text == "无" || lblPhone.Text == "无")
            {
                ScriptManager.RegisterClientScriptBlock(UpdatePanel1, typeof(UpdatePanel), null, "<script>alert('您的信息不完整!')</script>", false);
                return false;
            }
            od.UserID = ui.ID;
            od.UserName = Context.User.Identity.Name;//用户名
            od.AcceptPeople = userAddr[0];//姓名
            od.Province = userAddr1[0];//省
            od.City = userAddr1[1];//市
            od.County = userAddr1[2];//区/县
            od.DetailStreet = userAddr1[3];//街道地址
            od.ZipCode = lblZipCode.Text;//邮编
            od.AcceptPeopleTel = lblPhone.Text;//电话
            #region 是否开发票
            if (cbNeedIvoice.Checked)
            {
                od.NeedIvoice = cbNeedIvoice.Checked;
                od.IvoiceTitle = txtInvoiceTitle.Text.Trim();
                od.IvoiceContent = cblIvoice.SelectedValue;
            }
            else
            {
                od.NeedIvoice = false;
                od.IvoiceTitle = "";
                od.IvoiceContent = "";
            }
            #endregion
            #region 送货时间
            if (rblSendTimeRange.SelectedIndex == 3)
            {
                od.SendDateRange = txtSpecialTime.Text.Trim();
            }
            else
            {
                od.SendDateRange = rblSendTimeRange.SelectedValue;
            }
            #endregion
            od.OrderCreateDate = DateTime.Now;
            od.TotalPrice = GetTotal("TotalPrice");
            od.State = Model.Enumerations.OrderStatusType.PayedFindGoods.ToString();//订单状态

            od.State = Model.Enumerations.OrderStatusType.PayedFindGoods.ToString();

            od.AcceptType = 0;//sendWay有待扩展
            od.IsFenceMoney = false;//有待扩展
            od.FenceMoney = 0;//有待扩展
            od.PostPrice = 0;//有待扩展
            return true;
        }
        #endregion

        #region 页面数据处理
        /// <summary>
        /// 插入一个新的地址
        /// </summary>
        /// <param name="ui"></param>
        /// <param name="alb"></param>
        /// <param name="al"></param>
        private void AddNewAddress(GoShopping.Model.UserInfo ui, GoShopping.BLL.ProfileInfo.AddressListBean alb, GoShopping.Model.AddressList al)
        {
            al.UserID = Convert.ToInt32(ui.ID);
            al.AcceptPeople = txtFirstName.Text.Trim();
            al.ProvinceID = Convert.ToInt32(ProvinceSelect.Items[ProvinceSelect.SelectedIndex].Value);
            al.CityID = Convert.ToInt32(Request.Form["ctl00$ContentPlaceHolder1$Wizard1$CitySelect"]);
            al.CountyID = Convert.ToInt32(Request.Form["ctl00$ContentPlaceHolder1$Wizard1$CountySelect"]);
            al.DetailStreet = txtAddress1.Text.Trim();
            al.ZipCode = txtZip.Text.Trim();
            al.AcceptPeopleMobileTel = txtPhone.Text.Trim();
            al.AcceptPeopleTel = txtFixedPhone.Text.Trim();
            alb.AddOneAddressList(al);
        }

        /// <summary>
        /// 得到Repeater中选中的项的文本
        /// </summary>
        /// <param name="Rpt">传入的Repeater对象</param>
        /// <returns>选中的文本</returns>
        private string GetRptSelected(Repeater Rpt)
        {
            foreach (RepeaterItem item in Rpt.Items)
            {
                if (item.FindControl("rbAddress") != null)
                {
                    //RadioButton rb = (RadioButton)item.FindControl("rbAddress");
                    if (((RadioButton)(item.FindControl("rbAddress"))).Checked == true)
                    {
                        string lblName = ((Label)item.FindControl("lblName")).Text;
                        string lblPro = ((Label)item.FindControl("lblPro")).Text;
                        string lblCity = ((Label)item.FindControl("lblCity")).Text;
                        string lblCounty = ((Label)item.FindControl("lblCounty")).Text;
                        string lblStreet = ((Label)item.FindControl("lblStreet")).Text;
                        string lblZipCode = ((Label)item.FindControl("lblZipCode")).Text;
                        string lblPhone = ((Label)item.FindControl("AcceptPeopleMobileTel")).Text;
                        if (((Label)item.FindControl("AcceptPeopleMobileTel")) == null)
                        {
                            string lblFixedPhone = ((Label)item.FindControl("AcceptPeopleTel")).Text;
                            return lblPro + " " + lblCity + " " + lblCounty + " " + lblStreet + " " + lblZipCode + " " + lblFixedPhone + " " + lblName;
                        }
                        return lblPro + " " + lblCity + " " + lblCounty + " " + lblStreet + " " + lblZipCode + " " + lblPhone + " " + lblName;

                    }
                }
            }
            return null;
        }

        /// <summary>
        /// 获取地址列表
        /// </summary>
        private void GetAddressList()
        {
            GoShopping.BLL.UserBean ub = new GoShopping.BLL.UserBean();
            GoShopping.Model.UserInfo ui = ub.GetOneUser(Context.User.Identity.Name);
            BLL.ProfileInfo.AddressListBean alb = new GoShopping.BLL.ProfileInfo.AddressListBean();
            Model.AddressList al = new AddressList();
            IList<Model.AddressList> iPro = alb.GetUserAddressList(ui.ID);
            RptAddress.DataSource = iPro;
            RptAddress.DataBind();
        }

        /// <summary>
        /// 获取地址列表并返回
        /// </summary>
        /// <returns></returns>
        private IList<GoShopping.Model.AddressList> GetAddressLists()
        {
            GoShopping.BLL.UserBean ub = new GoShopping.BLL.UserBean();
            GoShopping.Model.UserInfo ui = ub.GetOneUser(Context.User.Identity.Name);
            GoShopping.BLL.ProfileInfo.AddressListBean alb = new GoShopping.BLL.ProfileInfo.AddressListBean();
            IList<GoShopping.Model.AddressList> iAl = alb.GetUserAddressList(ui.ID);
            return iAl;
        }

        protected void cbNeedIvoice_CheckedChanged(object sender, EventArgs e)
        {
            txtInvoiceTitle.Enabled = this.cbNeedIvoice.Checked;
            cblIvoice.Enabled = this.cbNeedIvoice.Checked;
        }

        protected void rblSendTimeRange_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (rblSendTimeRange.SelectedIndex == 3)
            {
                txtSpecialTime.Enabled = true;
            }
            else
            {
                txtSpecialTime.Enabled = false;
            }
        }
        #endregion

        #region Common
        /// <summary>
        /// 购物车中商品的总价
        /// </summary>
        /// <returns></returns>
        private decimal? GetTotal()
        {
            decimal dc = 0;
            foreach (CartItem ci in Profile.grpShoppingCart.MyCart.Items)
            {
                dc += ci.ItemPrice;
            }
            return dc;
        }
        /// <summary>
        /// 得到总价和总数
        /// </summary>
        /// <param name="p">Flag to remark if it is price or count</param>
        /// <returns></returns>
        private decimal GetTotal(string p)
        {
            if (Profile.grpShoppingCart.MyCart.Items == null)
            {
                Profile.grpShoppingCart.MyCart.Items = new List<CartItem>();
            }
            switch (p)
            {
                case "TotalPrice":
                    {
                        decimal sum = 0;
                        foreach (CartItem ci in Profile.grpShoppingCart.MyCart.Items)
                        {
                            sum += ci.ItemPrice;
                        }
                        return sum;
                    }
                case "TotalContt":
                    {
                        int count = 0;
                        foreach (CartItem ci in Profile.grpShoppingCart.MyCart.Items)
                        {
                            count += ci.Count;
                        }
                        return count;
                    }
            }
            return 0;
        }
        #endregion

        #region 级联菜单处理
        /// <summary>
        /// 返回DropDownList的数据,CityOrCounty
        /// </summary>
        private void ResponseCityOrCounty()
        {
            string str = "";
            if (Request.QueryString["provinceId"] != null)
            {
                Response.Expires = -1;
                Response.ContentType = "text/xml";
                str = GetDropDownList(Request.QueryString["ProvinceId"], "proId");
                Response.Write(str);
                Response.End();
            }
            else if (Request.QueryString["cityId"] != null)
            {
                Response.Expires = -1;
                Response.ContentType = "text/xml";
                str = GetDropDownList(Request.QueryString["cityId"], "cityId");
                Response.Write(str);
                Response.End();
            }
        }
        BLL.SysInfo.AreaControl ac = new GoShopping.BLL.SysInfo.AreaControl();
        /// <summary>
        /// 初始化级联菜单
        /// </summary>
        void SetProvinceDDL()
        {
            Model.Province province = new Province();
            ProvinceSelect.DataTextField = "Name";
            ProvinceSelect.DataValueField = "ID";
            ProvinceSelect.DataSource = ac.GetAllProvince();
            ProvinceSelect.DataBind();

            CitySelect.DataTextField = "Name";
            CitySelect.DataValueField = "ID";
            if (ProvinceSelect.SelectedIndex >= 0)
            {
                CitySelect.DataSource = ac.GetProvinceCity(Convert.ToInt32(ProvinceSelect.Items[ProvinceSelect.SelectedIndex].Value));
                CitySelect.DataBind();
            }

            CountySelect.DataTextField = "Name";
            CountySelect.DataValueField = "ID";
            if (CitySelect.SelectedIndex >= 0)
            {
                CountySelect.DataSource = ac.GetCityCounty(Convert.ToInt32(CitySelect.Items[CitySelect.SelectedIndex].Value));
                CountySelect.DataBind();
            }
        }
        /// <summary>
        /// 处理页面返回的DropDownList数据以确定返回的数据
        /// </summary>
        /// <param name="id"></param>
        /// <param name="flag"></param>
        /// <returns></returns>
        private string GetDropDownList(string id, string flag)
        {
            string str = "";
            switch (flag)
            {
                case "proId":
                    {
                        CitySelect.Items.Clear();
                        IList<Model.City> iCity = ac.GetProvinceCity(Convert.ToInt32(id));
                        str += "<city>";
                        for (int i = 0; i < iCity.Count; i++)
                        {
                            str += "<cl>" + iCity[i].Name + "," + iCity[i].ID + "</cl>";
                        }
                        str += "</city>";
                    } break;
                case "cityId":
                    {
                        CountySelect.Items.Clear();
                        IList<Model.County> iCounty = ac.GetCityCounty(Convert.ToInt32(id));
                        str += "<county>";
                        for (int i = 0; i < iCounty.Count; i++)
                        {
                            str += "<ct>" + iCounty[i].Name + "," + iCounty[i].ID + "</ct>";
                        }
                        str += "</county>";
                    } break;
                default: break;
            }
            return str;
        }
        #endregion

        #region 页面样式处理
        /// <summary>
        /// 设置Wizard文字
        /// </summary>
        private void SetWizardStyle()
        {
            Wizard1.StartNextButtonText = "下一步";
            Wizard1.StepNextButtonText = "下一步";
            Wizard1.StepPreviousButtonText = "上一步";
            Wizard1.CancelButtonText = "取消";
            Wizard1.FinishCompleteButtonText = "完成";
            Wizard1.FinishPreviousButtonText = "上一步";
        }
        #endregion
    }
}
